package org.andao.commons.taglib.function;

import java.text.ParseException;
import java.util.List;

import org.andao.commons.cache.CacheAppManager;
import org.andao.commons.model.ClassRoomCourse;
import org.andao.commons.model.Dictionary;
import org.andao.core.cache.EhCacheManager;
import org.andao.core.config.Constants;
import org.andao.core.utils.ExDateUtils;
import org.andao.core.utils.ExStringUtils;
import org.andao.core.utils.FileUtils;
import org.andao.security.SpringSecurityHelper;
import org.andao.security.cache.CacheSecManager;
import org.andao.security.model.Resource;
import org.andao.security.model.User;





/**
 * 自定义jstl函数.
 * 
 * @author Marco.hu(hzg139@163.com) 
 */
public class JstlCustomFunction {
	
	/**
	 * 转换日期为星期几
	 * @param dayStr
	 * @return
	 * @throws ParseException 
	 */
	public static String convertDay2Week(String dayStr) throws ParseException{
		return ExDateUtils.convertDay2Week(ExDateUtils.DATE_FORMAT.parse(dayStr));
	}
	
	/**
	 * 格式化文件大小为 KB,MB,GB
	 * @param filesize
	 * @return
	 */
	public static String formatFileSize(Long filesize) {
		return FileUtils.getHumanReadableFileSize(filesize);
	}
	
	/**
	 * 通过字典编码与值查找字典名称
	 * @param dictionaryCode 字典码
	 * @param value 字典值
	 * @return
	 */
	public static String dictionaryCode2Value(String dictionaryCode,String value){
		//从缓存中读取数据
		List<Dictionary> children  = CacheAppManager.getChildren(dictionaryCode);
		String values              = "";
		if(null != children ){
			for(Dictionary childDict : children){
				if(childDict.getIsUsed().equals(Constants.BOOLEAN_YES)){ //启用
					if(ExStringUtils.isNotEmpty(value)){ //默认值
						/*if(value.equals(childDict.getDictValue())){ //相等返回字典名
							return childDict.getDictName();
						}*/
						//if(value.split("\\,").length>0){//如果传入的多个值，则遍历
							for(int i=0;i<value.split("\\,").length;i++){
								if(value.split("\\,")[i].equals(childDict.getDictValue())){
									values += childDict.getDictName();
									if(i<value.split("\\,").length-1){
										values += ",";
									}
								}								
							}
							
						//}						
					}
				}
			}
		}
		//if (values.length()>0) {
		//	return values.substring(1);		
		//}else {
			return values;		
		//}
		
	}
	
	public static String dictionaryValue2Code(String dictionaryCode,String code){
		//从缓存中读取数据
		List<Dictionary> children  = CacheAppManager.getChildren(dictionaryCode);
		String values              = "";
		if(null != children ){
			for(Dictionary childDict : children){
				if(childDict.getIsUsed().equals(Constants.BOOLEAN_YES)){ //启用
					if(ExStringUtils.isNotEmpty(code)){ //默认值						
							for(int i=0;i<code.split("\\,").length;i++){
								if(code.split("\\,")[i].equals(childDict.getDictName())){
									values += childDict.getDictValue();
									if(i<code.split("\\,").length-1){
										values += ",";
									}
								}								
							}
				
					}
				}
			}
		}
	
	return values;		
				
	}
	
	public static String code2Course(String time, String phase, String day, List<ClassRoomCourse> courseList){
	    for(ClassRoomCourse course : courseList){
	        if(course.getTime().equals(time) && course.getPhase().equals(phase) && course.getDay().equals(day)){
	            return course.getCourse();
	        }
	    }
	    return "";
	}
	/**
	 * 传递一个资源编码,判断当前登录用户是否有权限
	 * @param funcCode
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static boolean hasAuth(String funcCode) {
		// 用户有权限的id		
		//Map<String, Object> userMap = UserDetailsServiceImpl.getUserMap();
		User user = SpringSecurityHelper.getCurrentUser();
		//if(null != userMap){
			String rightIds = user.getUserRightsIds();
			List<Resource> all = (List<Resource>)EhCacheManager.getCache(CacheSecManager.CACHE_SEC_RESOURCE).get(CacheSecManager.CACHE_SEC_RESOURCE);
			for(Resource  r : all) {
				if(funcCode.equalsIgnoreCase(r.getResourceCode())) {
					return rightIds.indexOf(r.getResourceid())>=0;
				}
			}
		//}
		
		return false;
	}
	
	/**
	 * 将组织|角色|用户的id 转换为名称 用“,”隔开
	 * @param type --> org | user | role
	 * @param ids
	 * @return
	 */
	public static String ids2Names(String type,String ids) {
		return CacheSecManager.ids2names(type, ids);
	}
	/**
	 * 资源路径转换为资源名称
	 * @param resourcePath
	 * @return
	 */
	public static String resourcePath2Names(String resourcePath){
		@SuppressWarnings("unchecked")
		List<Resource> all = (List<Resource>)EhCacheManager.getCache(CacheSecManager.CACHE_SEC_RESOURCE).get(CacheSecManager.CACHE_SEC_RESOURCE);
		for(Resource  r : all) {
			if(resourcePath.indexOf(r.getResourcePath())>-1){
				if(null != r.getParent()){
					return r.getParent().getResourceName()+">"+r.getResourceName();
				}else{
					return r.getResourceName();
				}
				
			}
		}
		return "其他";
	}
	
	/**
	 * 通过Step 获取流程相关参数
	 * @return
	 * @throws Exception
	 */
	/*
	public static String wfAttr(HibernateStep step, String attrName) throws Exception{
		Workflow wf = new BasicWorkflow(SpringSecurityHelper.getCurrentUser().getResourceid());
		HibernateWorkflowEntry entry = step.getEntry();
		String workflowname = entry.getWorkflowName();
		WorkflowDescriptor wfdescriptor = wf.getWorkflowDescriptor(workflowname);
		
		if("wfname".equalsIgnoreCase(attrName)) {//获取流程定义名称
			Object wfname = wfdescriptor.getMetaAttributes().get("name");
			return wfname == null ? "" : wfname.toString();
		}else if("wfcnname".equalsIgnoreCase(attrName)){//获取流程定义中文名称
			Object wfcnname = wfdescriptor.getMetaAttributes().get("cnname");
			return wfcnname == null ? "" : wfcnname.toString();
		}else if("wfurl".equalsIgnoreCase(attrName)) {//获取流程定义执行URL
			Object url = wfdescriptor.getMetaAttributes().get("url");
			return url == null ? "" : url.toString();
		}else if("curname".equalsIgnoreCase(attrName)) {//获取获取当前操作人
			int  currentStepId = entry.getCurrentSteps().get(0).getStepId();
			String currentStepName = wfdescriptor.getStep(currentStepId).getName();
			return currentStepName;
		}else if("spname".equalsIgnoreCase(attrName)) {//获取流程实例当前步骤
			int  stepId = step.getStepId();
			String stepName = wfdescriptor.getStep(stepId).getName();
			return stepName;
		}else if("wftype".equalsIgnoreCase(attrName)) {//获取流程实例名称
			return workflowname;
		}
		return null;
	}
	*/
}
